const app = getApp();
const Controller = require('../controllers/controllers.js').controller;
Page({
  data: {
      title:'搜索',
      searchstory:[],
      inputValue:'',
  }, 
  onLoad: function (options) {
    this.setData({
      inputValue:options.inputValue
    })
  },
  onShow() {
      //从本地获取搜索记录
      let searchstory = wx.getStorageSync('searchData');
          console.log('从本地获取搜索记录searchstory',searchstory)

      if (searchstory && searchstory.length > 0) {
          //进行倒序
          searchstory = searchstory.reverse();
      }
      this.setData({
          searchstory: searchstory,
          inputValue: '',
          focusbool:false
      })
  },
  onReady() {
      
  },
  onReachBottom: function () {

  },

  bindInput(e){
    var value=e.detail.value || ''
    if(value){
      this.setData({
        inputValue: value
      })
    }
  },
  searchvalue(e) {
    var value=e.currentTarget.dataset.search;
    wx.navigateTo({
      url: '/pages/lists/lists?search=' + value
    });
  },
  searchSubmit(e){
    var _SearchValue=this.data.inputValue;
    let localStorageValue = [];
    if (_SearchValue != '') {
        //添加搜索历史记录
        //调用API从本地缓存中获取数据
        localStorageValue = wx.getStorageSync('searchData') || [];
        let tempSearchData = [];
        //过滤历史列表中相同的搜索记录
        for (let item of localStorageValue) {
            if (item != _SearchValue) {
                tempSearchData.push(item); 
            }
        }
        //添加搜索文本进历史记录
        tempSearchData.push(_SearchValue);
        //保存至从本地缓存
        wx.setStorageSync('searchData', tempSearchData);
        
    }
    //跳转列表
      wx.navigateTo({
          url: "/pages/lists/lists?search=" + _SearchValue
      });
  },
  delete(e){
    var _SearchValue=e.currentTarget.dataset.search;
    let localStorageValue = [];
    if (_SearchValue != '') {
        localStorageValue = wx.getStorageSync('searchData') || [];
        var index = localStorageValue.indexOf(_SearchValue);
        localStorageValue.splice(index, 1)
        //保存至从本地缓存
        wx.setStorageSync('searchData', localStorageValue);
        this.setData({
            searchstory: localStorageValue.reverse()
        });
    }
  },

  onShareAppMessage: function (e) {
    
  },
  onShareTimeline: function (e) {
   
  },
})